import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, Like, FindOptionsWhere } from 'typeorm';
import { Order } from '../entities/order.entity';

export interface FindAllQuery {
  name?: string;
  phone?: string;
  orderNumber?: string;
  page?: number;
  size?: number;
}

export interface FindAllResponse {
  data: Order[];
  total: number;
}

@Injectable()
export class OrderService {
  constructor(
    @InjectRepository(Order)
    private orderRepository: Repository<Order>,
  ) {}

  async findAll(query: FindAllQuery): Promise<FindAllResponse> {
    const { name, phone, orderNumber, page = 1, size = 10 } = query;
    const where: FindOptionsWhere<Order> = { isDeleted: false };

    if (name) {
      where.name = Like(`%${name}%`);
    }
    if (phone) {
      where.phone = Like(`%${phone}%`);
    }
    if (orderNumber) {
      where.orderNumber = Like(`%${orderNumber}%`);
    }

    const [orders, total] = await this.orderRepository.findAndCount({
      where,
      relations: ['creator', 'customer'],
      skip: (page - 1) * size,
      take: size,
      order: {
        createdAt: 'DESC',
      },
    });

    return {
      data: orders,
      total,
    };
  }
}
